﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using com.amazon.s3;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Configuration;
using System.Xml.Serialization;
using System.IO;

namespace Tetris
{
    /// <summary>
    /// Summary description for Service1
    /// </summary>
    [WebService(Namespace = "http://benfulton.net/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class TetrisScore : System.Web.Services.WebService
    {
        private static readonly string awsAccessKeyId = ConfigurationSettings.AppSettings["S3Access"];
        private static readonly string awsSecretAccessKey = ConfigurationSettings.AppSettings["S3Secret"];
        private static readonly string awsScoreBucket = ConfigurationSettings.AppSettings["ScoreBucket"];

        AWSAuthConnection conn = new AWSAuthConnection(awsAccessKeyId, awsSecretAccessKey);
        [WebMethod]
        public void SaveScore( string name, long score)
        {
            ListAllMyBucketsResult result = conn.listAllMyBuckets();
            if (result.Buckets.Length == 0)
            {
                conn.createBucket(awsScoreBucket, null);
            }

            List<long> scores = ListScores(name);
            scores.Add(score);
            XmlSerializer serializer = new XmlSerializer(typeof(List<long>));
            StringWriter writer = new StringWriter();
            serializer.Serialize(writer, scores);
            conn.put(awsScoreBucket, name, writer.ToString(), null, null);
        }

        [WebMethod]
        public List<long> ListScores(string name)
        {
            GetObjectResult obj = conn.get(awsScoreBucket, name);
            ListBucketResult bucket = conn.listBucket(awsScoreBucket, null, null, 5);
            ASCIIEncoding ae = new ASCIIEncoding();
            XmlSerializer serializer = new XmlSerializer(typeof(List<long>));
            StringReader reader = new StringReader(ae.GetString(obj.Data));
            return serializer.Deserialize(reader) as List<long>;
        }
    }
}
